﻿// MainForm.xaml.cs
// Aleksei Vassiljev
// {4DC17B88-5237-4e95-A60D-72988F554D4F}

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Threading;
using System.Diagnostics;
using OracleTools.Core;
using OracleTools.OracleHomeSelector.Resources;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;

namespace OracleTools.OracleHomeSelector
{
    /// <summary>
    /// Interaction logic for MainForm.xaml
    /// </summary>
    public partial class MainForm : Window
    {
        private OraMaster oramaster;
        private BackgroundWorker bgwChangeHome;

        public static RoutedCommand ShowInfoCommand = new RoutedCommand();
        public static RoutedCommand ChangeHomeCommand = new RoutedCommand();
        public static RoutedCommand ShowHelpCommand = new RoutedCommand();
        public static RoutedCommand ChangeNlsLangCommand = new RoutedCommand();
        public static RoutedCommand ShowEditNlsLangCommand = new RoutedCommand();

        private bool IsChangingHome = false;

        private SavedNlsLangs m_savedNlsLangs;
        string m_sPrevSelectedNlsLang = "";


        public MainForm()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainForm_Loaded);
            BeforeWorking();
        }

        


        void MainForm_Loaded(object sender, RoutedEventArgs e)
        {
            oramaster = OraMaster.GetInstance();

            // Event handlers
            cboHomes.SelectionChanged += new SelectionChangedEventHandler(cboHomes_SelectionChanged);
            oramaster.CurrentHomeChanged +=
                new EventHandler<OraEventArgs>((sx, ex) => cboHomes.SelectedItem = ex.CurrentHome);

            // Background process that changes the home
            bgwChangeHome = new BackgroundWorker();
            bgwChangeHome.DoWork += new DoWorkEventHandler(bgwChangeHome_DoWork);
            bgwChangeHome.RunWorkerCompleted +=
                new RunWorkerCompletedEventHandler((sx, ex) => AfterWorking());

            m_savedNlsLangs = SavedNlsLangs.GetInstance();
            //m_savedNlsLangs.NlsLangs.ForEach(x => cboNlsLang.Items.Add(x));
            
            cboNlsLang.ItemsSource = m_savedNlsLangs.NlsLangs; // I don't know why, but calling Items.Refresh freezes combo box first open
                                                                 // for 4-5 seconds.




            cboNlsLang.SelectionChanged += new SelectionChangedEventHandler((sx, ex) =>
            {
                if (ex.AddedItems.Count > 0)
                    m_sPrevSelectedNlsLang = ex.AddedItems[0].ToString();
            });
            
            /*cboNlsLang.KeyUp += new KeyEventHandler((sx, ex) =>
            {
                if (ex.Key == Key.Delete && oramaster.LocaleNlsLang != m_sPrevSelectedNlsLang && cboNlsLang.Text == "")
                {
                    m_savedNlsLangs.RemoveItem(m_sPrevSelectedNlsLang);
                    cboNlsLang.Items.Remove(m_sPrevSelectedNlsLang);
                    cboNlsLang.SelectedItem = oramaster.LocaleNlsLang;
                }
            });*/


            // Load list of homes
            new Thread(() =>
                {
                    Action action = () =>
                    {
                        oramaster.LoadData();
                        cboHomes.ItemsSource = oramaster.Homes;
                        cboHomes.SelectedItem = oramaster.CurrentHome;

                        foreach (OraHome home in oramaster.Homes)
                        {
                            m_savedNlsLangs.AddItem(home.NlsLang);
                        }
                        //MessageBox.Show(Environment.GetEnvironmentVariable("NLS_LANG", EnvironmentVariableTarget.User));
                        m_savedNlsLangs.AddItem(Environment.GetEnvironmentVariable("NLS_LANG", EnvironmentVariableTarget.User));
                        //if(n > -1)
                        //    cboNlsLang.Items.Insert(n, oramaster.LocaleNlsLang);
                        //cboNlsLang.SelectedItem = oramaster.LocaleNlsLang;

                        AfterWorking();

                    };
                    Dispatcher.Invoke(action);
                }).Start();
        }

        void bgwChangeHome_DoWork(object sender, DoWorkEventArgs e)
        {
            Action action = () =>
                {
                    oramaster.SetAsCurrent(e.Argument as OraHome);
                };
            Dispatcher.Invoke(action);
        }


        private void BeforeWorking()
        {
            IsChangingHome = true;
            this.Cursor = Cursors.Wait;

            cmdChangeHome.Style = (Style)Application.Current.Resources[ResID.STYLE_SET_BUTTON_WORKING];
            cboHomes.IsEnabled = false;
            cmdInfo.IsEnabled = false;
        }
        private void AfterWorking()
        {
            MakeButtonCurrent(true);
            cboHomes.IsEnabled = true;
            cmdInfo.IsEnabled = true;

            cboNlsLang.Items.Refresh();
            cboNlsLang.SelectedItem = oramaster.LocaleNlsLang;
            
            this.Cursor = Cursors.Arrow;
            IsChangingHome = false;

        }
        private void MakeButtonCurrent(bool pbIsCurrentSelected)
        {
            if (pbIsCurrentSelected)
            {
                cmdChangeHome.Style = (Style)Application.Current.Resources[ResID.STYLE_SET_BUTTON_CURRENT];
            }
            else
            {
                cmdChangeHome.Style = (Style)Application.Current.Resources[ResID.STYLE_SET_BUTTON_NOT_CURRENT];
            }
        }

        private void ShowInfoCommandExecute(object sender, ExecutedRoutedEventArgs e)
        {
            HomeInfoForm frm = new HomeInfoForm(oramaster);
            frm.SelectedHome = cboHomes.SelectedItem as OraHome;
            frm.ShowDialog();
        }
        private void ChangeHomeCommandExecute(object sender, ExecutedRoutedEventArgs e)
        {
            BeforeWorking();
            bgwChangeHome.RunWorkerAsync(cboHomes.SelectedItem);
        }
        private void CommandCanExecuteIfNotWorkingState(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = !IsChangingHome;
        }
        private void ShowHelpCommandExecute(object sender, ExecutedRoutedEventArgs e)
        {
            Process.Start(ResID.site_url);
        }

        // Command - Change Nls Lang
        private void ChangeNlsLangCommandExecute(object sender, ExecutedRoutedEventArgs e)
        {
            string lang = cboNlsLang.Text.Trim();
#if DEBUG
            Debug.WriteLine("Change lang to {0}", lang);
#endif   
            //int n = m_savedNlsLangs.AddItem(lang);
            //if(n > -1)
            //    cboNlsLang.Items.Insert(n, lang);

            new Thread(() =>
                {
                    Action action = () => oramaster.ChangeNlsLang(lang);
                    Dispatcher.Invoke(action);
                }).Start();

        }
        private void ChangeNlsLangCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (oramaster != null)
                e.CanExecute = (oramaster.LocaleNlsLang != cboNlsLang.Text) && !string.IsNullOrWhiteSpace(cboNlsLang.Text);
        }

        // Command - Show Edit NLS List Form
        private void ShowEditNlsLangCommandExecute(object sender, ExecutedRoutedEventArgs e)
        {
            NlsListForm frm = new NlsListForm(m_savedNlsLangs, oramaster);
            bool? result = frm.ShowDialog();
            if (result.HasValue && result.Value)
            {
                new Thread(() =>
                {
                    Action action = () =>
                    {
                        cboNlsLang.Items.Refresh();
                        cboNlsLang.SelectedItem = oramaster.LocaleNlsLang;
                    };
                    Dispatcher.Invoke(action);
                }).Start();

                
            }
        }

        void cboHomes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            OraHome newHome = e.AddedItems[0] as OraHome;
            MakeButtonCurrent(newHome.IsCurrent);
        }
    }
}
